package top.arryweb.application.common.config;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Description Redis配置
 * @Author mac
 * @Date 2021/5/27
 **/
@Configuration
public class RedisConfiguration {

  @Bean
  public RedisTemplate<String, Object> redisTemplate(
      RedisConnectionFactory redisConnectionFactory) {
    //使用FastJson进行序列化(方便获取被序列化后的json格式对象)
    FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(
        Object.class);
    //配置序列化的方式
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    //使用FastJson将对象序列化成json格式的字符串
    fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteClassName);
    serializer.setFastJsonConfig(fastJsonConfig);
    //指定序列化白名单（增加安全性）
    ParserConfig.getGlobalInstance().addAccept("top.arryweb.application");
    //创建RedisTemplate
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    //设置redis连接
    redisTemplate.setConnectionFactory(redisConnectionFactory);
    //使用FastJson序列化 key-value
    redisTemplate.setDefaultSerializer(serializer);

    // 设置值（value）的序列化采用FastJsonRedisSerializer。
//    redisTemplate.setValueSerializer(serializer);
//    redisTemplate.setHashValueSerializer(serializer);
    // 设置键（key）的序列化采用StringRedisSerializer。
//    redisTemplate.setKeySerializer(new StringRedisSerializer());
//    redisTemplate.setHashKeySerializer(new StringRedisSerializer());

    return redisTemplate;

  }

  @Bean
  @ConditionalOnMissingBean(StringRedisTemplate.class)
  public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
    FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<Object>(Object.class);
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteClassName);
    serializer.setFastJsonConfig(fastJsonConfig);
    StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
    stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
    stringRedisTemplate.setDefaultSerializer(serializer);
    return stringRedisTemplate;
  }
}

/**
 * Redis 序列化方式StringRedisSerializer、FastJsonRedisSerializer和KryoRedisSerializer
 * https://my.oschina.net/xiaolyuh/blog/3109282
 */
